<template>
  <view class="page">
    <scroll-view class="scroll-view" scroll-y scroll-with-animation :scroll-top="top">
      <view style="padding: 30rpx 30rpx 240rpx">
        <view class="message" v-for="(item, index) in list" :key="index">
          <!-- <view class="ip">
                        {{ item.ip }}
                    </view> -->
          <view class="message_c">
            <view class="message_c_title">
              <image :src="_selfAvatar" class="avatar" mode="widthFix"> </image>
              <view class="content">
                {{ item.content }}
              </view>
            </view>

            <view class="answer" v-for="(value, key, index) in item.result" :key="index">
              <view>{{ value.titleName }}</view>
              <view @click="openWebView(value.imageUrl)" class="answer-image">
                {{ value.imageUrl }}
              </view>
              <view @click="openWebView(value.contentUrl)" class="answer-image"
                >{{ value.contentUrl }}
              </view>
            </view>
            <!-- <image :src="item.avatar" v-if="item.userType === 'self'" class="avatar" mode="widthFix">
                        </image> -->
          </view>
        </view>
      </view>
    </scroll-view>
    <view class="tool">
      <textarea type="text" v-model="content" class="input" @confirm="send" />
      <!-- <textarea v-model="content" placeholder="请输入内容"></textarea> -->
      <button class="mini-btn" type="default" size="mini" @click="sendProbleMessage">发送</button>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted, nextTick } from 'vue'
import { getSendProblemResultAPI } from '@/services/charge'

// import {
//     useAvatarStore
// } from '/stores/avatar';
// 获取 store 实例
// const avatarStore = useAvatarStore();

// 定义响应式数据
const content = ref('')
const list = ref([])
const top = ref(0)
const socket = ref(null) // WebSocket实例
const _selfAvatar = '/static/images/faceImg.png'

// 模拟数据初始化
onMounted(() => {
  // 创建 WebSocket 连接
  // socket.value = new WebSocket('ws://192.168.31.182:3000'); // 连接到后端 WebSocket 服务器
  // WebSocket 连接成功
  // socket.value.onopen = () => {
  //     console.log('WebSocket连接成功');
  // };
  // 接收到消息时将其添加到消息列表
  // WebSocket 接收消息处理
  // socket.value.onmessage = (event) => {
  //     const msg = JSON.parse(event.data); // 解析 JSON 数据
  //     console.log("接受消息", msg); // 直接打印对象
  //     list.value.push(msg);
  //     nextTick(() => {
  //         scrollToBottom(); // 确保在渲染完成后滚动到底部
  //     });
  // };
  // WebSocket 连接错误处理
  // socket.value.onerror = (error) => {
  //     console.error('WebSocket 连接错误', error);
  // };
  // WebSocket 连接关闭时的处理
  // socket.value.onclose = () => {
  //     console.log('WebSocket 连接关闭');
  // };
})

// 发送消息
const sendProbleMessage = async () => {
  if (content.value.trim()) {
    // 发送消息到服务器
    const data = {
      content: content.value, // 将自己的消息添加到列表
      userType: 'self',
      avatar: _selfAvatar,
    }

    //list.value.push(data);
    const sendRes = await getSendProblemResultAPI()
    console.log(sendRes)

    if (sendRes.code === 0) {
      let jsonKey = content.value
      const jsonValue = sendRes.dataList
      list.value.push({ content: jsonKey, result: jsonValue })
      // 添加到列表.
      // list.value.push(Json.stringify(content.vaule):sendRes.datalist );
      console.log('我接受的消息' + list.value)
      // 清空输入框
      content.value = ''
    } else {
      //socket.value.send(JSON.stringify(data)); // 发送一个 JSON 格式的字符串
      // console.log("我发送的消息" + content.value)
      // content.value = ''; // 清空输入框
      nextTick(() => {
        scrollToBottom() // 确保在渲染完成后滚动到底部
      })
    }
  }
}

// 滚动到最底部
function scrollToBottom() {
  top.value = list.value.length * 1000
}

const openWebView = (url: string) => {
  uni.navigateTo({
    url: `/pages/webview/webview?url=${encodeURIComponent(url)}`,
  })
}
</script>

<style lang="scss" scoped>
.scroll-view {
  /* #ifdef H5 */
  height: calc(100vh - 44px);
  /* #endif */
  /* #ifndef H5 */
  height: 100vh;
  /* #endif */
  background: #eee;
  box-sizing: border-box;
}

.message {
  display: flex;
  align-items: flex-start;
  margin-bottom: 30rpx;
  flex-direction: column;

  .message_c {
    width: 100%;
    display: flex;
    flex-direction: column;
    align-items: flex-start;

    .message_c_title {
      display: flex;
      align-items: flex-start;
    }

    .avatar {
      width: 80rpx;
      height: 80rpx;
      border-radius: 10rpx;
      margin-right: 30rpx;
    }

    .content {
      word-break: break-all;
      min-height: 80rpx;
      max-width: 60vw;
      box-sizing: border-box;
      font-size: 28rpx;
      line-height: 1.3;
      padding: 20rpx;
      border-radius: 10rpx;
      background: #fff;

      image {
        width: 200rpx;
      }
    }

    &.self {
      justify-content: flex-end;

      .avatar {
        margin: 0 0 0 30rpx;
      }

      .content {
        position: relative;

        &::after {
          position: absolute;
          content: '';
          width: 0;
          height: 0;
          border: 16rpx solid transparent;
          border-left: 16rpx solid #fff;
          right: -28rpx;
          top: 24rpx;
        }
      }
    }

    &.friend {
      .content {
        position: relative;

        &::after {
          position: absolute;
          content: '';
          width: 0;
          height: 0;
          border: 16rpx solid transparent;
          border-right: 16rpx solid #fff;
          left: -28rpx;
          top: 24rpx;
        }
      }
    }
  }
}

.answer {
  display: flex;
  width: 100%;
  flex-direction: column;
  flex-wrap: wrap;
  align-items: flex-start;
  justify-content: flex-start;
  background: #fff;
  align-items: flex-start;
  justify-content: flex-start;
  margin-top: 8px;
  padding: 0.4rem;
  border-radius: 0.4rem;

  .answer-image {
    width: 100%;
    height: 1.5rem;
    line-height: 1.5rem;
    display: flex;
    flex-direction: row;
    flex-wrap: wrap !important;
    overflow: scroll;
  }
}

.tool {
  position: fixed;
  width: 100%;
  min-height: 120rpx;
  left: 0;
  bottom: 0;
  background: #fff;
  display: flex;
  align-items: flex-start;
  box-sizing: border-box;
  padding: 20rpx 24rpx 20rpx 40rpx;
  padding-bottom: calc(20rpx + constant(safe-area-inset-bottom) / 2) !important;
  padding-bottom: calc(20rpx + env(safe-area-inset-bottom) / 2) !important;

  .input {
    background: #eee;
    border-radius: 10rpx;
    height: 70rpx;
    margin-right: 30rpx;
    flex: 1;
    padding: 0 20rpx;
    box-sizing: border-box;
    font-size: 28rpx;
  }

  .thumb {
    width: 64rpx;
  }
}
</style>
